package com.zam.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zam.comment.Constants;
import com.zam.exception.ServiceException;
import com.zam.mapper.MenuMapper;
import com.zam.mapper.RoleMapper;
import com.zam.mapper.SysRoleMenuMapper;
import com.zam.mapper.UserMapper;
import com.zam.pojo.Menu;
import com.zam.pojo.Role;
import com.zam.pojo.SysRoleMenu;
import com.zam.pojo.User;
import com.zam.service.UserService;
import com.zam.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.zam.comment.Constants.USER_NEWS_KEY;
import static com.zam.comment.Constants.USER_TOKEN_TIME;

/**
 * @author talent_dog
 * @description 针对表【ms_user】的数据库操作Service实现
 * @createDate 2023-12-04 11:04:05
 */

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;

    @Autowired
    private MenuMapper menuMapper;
    @Override
    public User login(String username, String password) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUsername, username).eq(User::getPassword, password);
        //判断用户是否存在
        User user = userMapper.selectOne(lambdaQueryWrapper);
        if (user == null) {
            return null;
        }

        //通过角色获取角色表的信息
        Role role = roleMapper.selectOne(new LambdaQueryWrapper<Role>().eq(Role::getFlag, user.getRole()));
        user.setRoleData(role);

        //通过角色id，先获取角色可以操作的菜单id，再获取菜单表的信息
        List<SysRoleMenu> sysRoleMenus = sysRoleMenuMapper.selectList(
                new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getRoleId, role.getId()));
        //菜单id集合
        List<Integer> collect = sysRoleMenus.stream().map(SysRoleMenu::getMenuId).collect(Collectors.toList());
        //通过菜单集合，获取菜单表的信息
        List<Menu> menus = menuMapper.selectList(new LambdaQueryWrapper<Menu>().in(Menu::getId, collect));
        //获取所有子菜单id
        List<Integer> menusID = menus.stream().filter(menu -> menu.getPid() != null).map(Menu::getId).collect(Collectors.toList());
        //将子菜单添加到父菜单中
        for (Menu menu : menus){
            menu.setChildren(menuMapper.selectList(new LambdaQueryWrapper<Menu>().eq(Menu::getPid, menu.getId()).in(Menu::getId, menusID)));
        }

        //由于已经将子菜单添加到父菜单中，因此需要将子菜单从菜单集合中移除
        menus.removeAll(menus.stream().filter(menu->menu.getPid()!=null).collect(Collectors.toList()));
        user.setMenuList(menus);

        extracted(password, user);

        return user;
    }

    private void extracted(String password, User user) {
        //手动设置token属性的值
        user.setToken(JwtUtil.createJwt(user.getId(), password));
        // 存入redis
        Map<String, Object> map = BeanUtil.beanToMap(user,new HashMap<>(),
                CopyOptions.create()
                        .setFieldValueEditor((filedName,filedValue)->{return filedValue==null?null:filedValue.toString();})
            );
        stringRedisTemplate.opsForHash().putAll(USER_NEWS_KEY + user.getId(),map);
        stringRedisTemplate.expire(USER_NEWS_KEY + user.getId(),USER_TOKEN_TIME, TimeUnit.MINUTES);
    }


}




